package hz.mobileproject.pda.model.attendancemanager.activity;

import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.text.SimpleDateFormat;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.app.MainApp;
import hz.mobileproject.pda.entity.MessageEvent;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.model.attendancemanager.adapter.AttendanceMsgLvAdapter;
import hz.mobileproject.pda.model.attendancemanager.bean.Rp_queryWork;
import hz.mobileproject.pda.model.attendancemanager.bean.Rq_loadDept;
import hz.mobileproject.pda.model.attendancemanager.bean.Rq_queryWork;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.tree.FileBean;
import hz.mobileproject.pda.tree.Node;
import hz.mobileproject.pda.ui.base.BaseActivity;
import hz.mobileproject.pda.ui.view.DeptSelectorDialog;
import hz.mobileproject.pda.ui.view.datepicker.CustomDatePicker;
import hz.mobileproject.pda.utils.HttpRqUtils;

@ContentView(R.layout.activity_attendance_msg)
public class AttendanceMsgActivity extends BaseActivity {
    @ViewInject(R.id.lv_attendance)
    private ListView lv_attendance;
    @ViewInject(R.id.smartLayout)
    private SmartRefreshLayout smartRefreshLayout;
    @ViewInject(R.id.iv_show_search)
    private ImageView iv_show_search;
    @ViewInject(R.id.ll_outgoing_search)
    private LinearLayout ll_outgoing_search;
    @ViewInject(R.id.tv_attendance_time_s)
    private TextView tv_attendance_time_s;
    @ViewInject(R.id.tv_dept_s)
    private TextView tv_dept_s;
    @ViewInject(R.id.tv_police_s)
    private EditText et_police_s;
    @ViewInject(R.id.ll_dept_selector)
    private LinearLayout ll_dept_selector;
    @ViewInject(R.id.tv_count)
    private TextView tv_count;

    private int mPageNum = 1;
    private AttendanceMsgLvAdapter mAdapter;
    private List<FileBean> mDeptList;
    private int mSelectedDeptID = 0;

    @Override
    protected void initData() {
        mAdapter = new AttendanceMsgLvAdapter(this);
        lv_attendance.setAdapter(mAdapter);
        loadDeptFromSer();
        queryWorkList();
    }

    @Event({R.id.iv_right_menu, R.id.iv_show_search, R.id.btn_search, R.id.tv_attendance_time_s, R.id.tv_dept_s})
    private void onViewClick(View v){
        switch (v.getId()){
            case R.id.btn_search:
                emptyData();
                queryWorkList();
                break;
            case R.id.iv_show_search:
                isShowSearch();
                break;
            case R.id.tv_attendance_time_s:
                showDatePicker(tv_attendance_time_s);
                break;
            case R.id.tv_dept_s:
                if (mDeptList == null) {
                    ToastUtils.showShort("未获取到部门数据");
                    return;
                }
                DeptSelectorDialog deptSelectorDialog = new DeptSelectorDialog(this, mDeptList);
                deptSelectorDialog.show();
                deptSelectorDialog.setOnPositiveBtnClick(new DeptSelectorDialog.OnPositiveBtnClick() {
                    @Override
                    public void onClick(DeptSelectorDialog dialog, Node node) {
                        dialog.dismiss();
                        tv_dept_s.setText(node.getName());
                        mSelectedDeptID = node.getId();
                    }
                });
                break;
        }
    }

    private void queryWorkList() {
        Rq_queryWork rq = new Rq_queryWork();
        rq.setCusNumber(MainApp.getInstance().getLoginUser().getCus_number() + "");
        rq.setPoliceCode(MainApp.getInstance().getLoginUser().getPolice_code());
        rq.setDeptId(MainApp.getInstance().getLoginUser().getDepartment_id() + "");
        rq.setPage(mPageNum);
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_ATTENDANCE_QUERY_WORK, rq, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                LogUtils.e(data);
                smartRefreshLayout.finishLoadmore();
                Rp_queryWork rp = mGson.fromJson(data, Rp_queryWork.class);
                if (rp == null || rp.data == null || rp.data.size() <= 0) {
                    ToastUtils.showShort("没有更多数据了");
                    return;
                }
                tv_count.setText(rp.count + "");
                mAdapter.addAll(rp.data);
                mPageNum++;
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                LogUtils.e(rtnCode + rtnMsg);
                ToastUtils.showShort("获取数据失败(" + rtnCode + "," + rtnMsg + ")");
                smartRefreshLayout.finishLoadmore();
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                LogUtils.e(ex.toString());
                ToastUtils.showShort("获取数据失败，请检查网络");
                smartRefreshLayout.finishLoadmore();
            }
        });
    }


    /**
     * 加载部门数据
     */
    private void loadDeptFromSer() {
        Rq_loadDept rq = new Rq_loadDept();
        rq.setPolice_code(MainApp.getInstance().getLoginUser().getPolice_code());
        rq.setDept_id(MainApp.getInstance().getLoginUser().getDepartment_id() + "");
        rq.setFlowTypeId(1);
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_LOAD_DEPT, rq, new CustomNetCallBack() {
            @Override
            public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
                List<FileBean> deptList = new Gson().fromJson(data, new TypeToken<List<FileBean>>() {
                }.getType());
                if (deptList == null || deptList.size() <= 0) {
                    ToastUtils.showShort("部门数据为空");
                    return;
                }
                mDeptList = deptList;
            }

            @Override
            public void onErrorFromSer(int rtnCode, String rtnMsg) {
                ToastUtils.showShort("服务器返回错误(" + rtnCode + "," + rtnMsg + ")");
            }

            @Override
            public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
                ToastUtils.showShort("连接服务器失败，请检查网络");
            }
        });
    }


    private void isShowSearch() {
        if (View.VISIBLE == ll_outgoing_search.getVisibility()) {
            ll_outgoing_search.setVisibility(View.GONE);
            iv_show_search.setImageBitmap(ImageUtils.getBitmap(R.mipmap.xiangxiajiantou));
        } else {
            ll_outgoing_search.setVisibility(View.VISIBLE);
            iv_show_search.setImageBitmap(ImageUtils.getBitmap(R.mipmap.xiangshangjiantou));
        }
    }


    private void showDatePicker(final TextView tv) {
        String selectTime = "";
        if (!StringUtils.isEmpty(tv.getText())) {
            selectTime = tv.getText().toString();
        } else {
            selectTime = TimeUtils.getNowString(new SimpleDateFormat("yyyy-MM-dd"));
        }
        CustomDatePicker customDatePicker = new CustomDatePicker(this, new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) { // 回调接口，获得选中的时间
                tv.setText(time.split(" ")[0]);
            }
        }, "1968-01-01 00:00", "2068-01-01 00:00"); // 初始化日期格式请用：yyyy-MM-dd HH:mm，否则不能正常运行
        customDatePicker.showSpecificTime(false); // 不显示时和分
        customDatePicker.setIsLoop(true); // 循环滚动
        customDatePicker.show(selectTime);
    }

    private void emptyData() {
        mPageNum = 1;
        tv_count.setText("0");
        mAdapter.deleteAll();
    }
}
